package com.question.utils;


import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {
	private static DataSource datasource  = new ComboPooledDataSource();
	private static ThreadLocal<Connection> threadlocal = new ThreadLocal<>();
	/**
	 * 该方法返回一个DataSource,连接池---MySQL
	 * @return DataSource
	 */
	public static DataSource  getDatasource() {
		return datasource;
	}
	/**
	 * 该方法获得连接对象
	 * @return Connection
	 */
	
	public static Connection getConnection() throws SQLException{
		Connection conn = threadlocal.get();
		if(conn == null) {
			conn = datasource.getConnection();
			threadlocal.set(conn);
		}
		return conn;
	}
	/**
	 * 开启事务
	 */
	public static void startTransaction() throws SQLException{
		Connection conn = threadlocal.get();
		if(conn != null) {
			conn.setAutoCommit(false);
		}
	}
	
	/**
	 * 回滚事务
	 */
	public static void rollback() throws SQLException{
		Connection conn = threadlocal.get();
		if(conn != null) {
			conn.rollback();
			
		}
	}
	/**
	 * 提交事务
	 * 关闭资源及从ThreadLocall中释放
	 */
	public static void commitAndRelease() throws SQLException{
		Connection conn = threadlocal.get();
		if(conn != null) {
			conn.commit();
			conn.close();
			threadlocal.remove();
		}
	}
}
